package com.tensquare.friend.service;

import com.tensquare.friend.client.UserClient;
import com.tensquare.friend.dao.FriendDao;
import com.tensquare.friend.dao.NoFriendDao;
import com.tensquare.friend.pojo.Friend;
import com.tensquare.friend.pojo.NoFriend;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

@Service
@Transactional
public class FriendService {
    @Autowired
    private FriendDao friendDao;

    @Autowired
    private NoFriendDao noFriendDao;

    @Autowired
    private UserClient userClient;

// todo @Transactional啥玩意
    public int addFriend(String userid,String friendid){

        //判断是否已经添加过此好友
        if(friendDao.count(userid,friendid)>0){
            return 0; //添加过好友了
        }

        //添加好友
        Friend f = new Friend();
        f.setUserid(userid);
        f.setFriendid(friendid);
        f.setIslike("0");

        friendDao.save(f);

        //如果对方已经添加自己为好友了，则修改状态
        if(friendDao.count(friendid,userid)>0){
            friendDao.updateIsLike(userid,friendid,"1");
            friendDao.updateIsLike(friendid,userid,"1");
        }

        //修改用户的关注数和粉丝数
        userClient.incFollowcount(userid,1);
        userClient.incFanscount(friendid,1);

        return 1;
    }

    /**
          * 向不喜欢列表中添加记录
          * @param userid
          * @param friendid
          */
    public void addNoFriend(String userid,String friendid){
        NoFriend noFriend=new NoFriend();
        noFriend.setUserid(userid);
        noFriend.setFriendid(friendid);
        noFriendDao.save(noFriend);
    }

    //删除好友
    public void deleteFriend(String userid,String friendid){
        friendDao.deleteFriend(userid,friendid);
        friendDao.updateIsLike(friendid,userid,"0");
        addNoFriend(userid,friendid);

        //修改用户的关注数和粉丝数
        userClient.incFollowcount(userid,-1);
        userClient.incFanscount(friendid,-1);
    }
}
